package com.liliudong.dynamicmybatis

import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.ui.Messages
import com.intellij.util.containers.stream
import org.apache.commons.lang.text.StrBuilder
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.util.*
import java.util.stream.Collectors

/**
 * 动态选择sqlaction
 * @author liudo
 * @date 2023/12/14
 * @constructor 创建[DynamicSelectSQLAction]
 */
class DynamicSelectSQLAction : AnAction() {
    override fun actionPerformed(event: AnActionEvent) {
        val editor = event.getRequiredData(CommonDataKeys.EDITOR)
        // 获取选中的文本
        val selectedText = editor.selectionModel.selectedText
        if (!selectedText.isNullOrEmpty()) {
            // 打印选中的文本内容
            val fields = selectedText.replace(Regex("\\s+"), "")
                    .split(",".toRegex())
                    .dropLastWhile { it.isEmpty() }
                    .toTypedArray()

            val generateSelect = generateSelect(fields)
            val clipboard = Toolkit.getDefaultToolkit().systemClipboard
            val stringSelection = StringSelection(generateSelect)
            clipboard.setContents(stringSelection, null)
            CopySuccessNotification.showCopySuccessNotification(editor.project)
        } else {
            Messages.showMessageDialog(editor.project, "You did not select text!", "Error", Messages.getErrorIcon())
        }

    }
}


/**
 * 生成查询
 * @param [sql] sql
 */
private fun generateSelect(fields: Array<String>): String {
    val builder = StrBuilder()
    builder.append("<if test=\"%s != null\">")
    builder.append("and %s = #{%s}")
    builder.append("</if>")
    return fields.stream().map { field: String ->
        if (field.contains("_")) {
            val split = field.split("_".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
            val attributeLower = Arrays.stream(split)
                    .map { item: String -> item.substring(0, 1).uppercase(Locale.getDefault()) + item.substring(1) }
                    .collect(Collectors.joining())
            val attribute = attributeLower.substring(0, 1).lowercase(Locale.getDefault()) + attributeLower.substring(1)
            return@map String.format(builder.toString(), attribute, field, attribute)
        }
        String.format(builder.toString(), field, field, field)
    }.collect(Collectors.joining("\n"))
}

